<template>
  <div class="avatar-management-container">
    <!-- 左右布局容器 -->
    <div class="main-layout">
      <!-- 左侧用户信息编辑 -->
      <div class="user-profile-section">
        <h2 class="section-title">用户信息编辑</h2>
        <div class="profile-editor">
          <!-- 头像上传模块 -->
          <div class="avatar-upload-enhanced">
            <el-upload
                class="avatar-uploader"
                :action="uploadImgServer"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :on-success="handleUploadSuccess"
                :auto-upload="true"
            >
              <template #trigger>
                <div class="avatar-preview-wrapper">
                  <el-image
                      :src="userForm.avatar"
                      class="current-avatar"
                      fit="cover"
                      :preview-src-list="[originalAvatar]"
                  >
                    <template #error>
                      <div class="error-overlay">
                        <el-icon>
                          <Picture/>
                        </el-icon>
                        <span>头像加载失败</span>
                      </div>
                    </template>
                  </el-image>
                  <div class="upload-mask">
                    <el-icon>
                      <Upload/>
                    </el-icon>
                    <span>点击更换头像</span>
                  </div>
                </div>
              </template>
            </el-upload>
          </div>

          <!-- 用户信息表单 -->
          <el-form :model="userForm" label-width="80px">
            <el-form-item label="用户账号">
              <el-input v-model="userForm.username" disabled/>
            </el-form-item>
            <el-form-item label="真实姓名">
              <el-input v-model="userForm.name"/>
            </el-form-item>
            <el-form-item label="联系电话">
              <el-input v-model="userForm.phone"/>
            </el-form-item>
            <el-form-item label="电子邮箱">
              <el-input v-model="userForm.email"/>
            </el-form-item>
          </el-form>
        </div>
        <div class="global-actions">
          <el-button
              type="primary"
              :icon="Check"
              :loading="isSaving"
              @click="updateUserInfo"
          >
            保存所有修改
          </el-button>
        </div>
      </div>

      <!-- 右侧AI头像生成 由于后端接口出现问题，暂时先去除该内容-->
<!--      <div class="ai-generation-section">-->
<!--        <h2 class="section-title">AI头像生成</h2>-->
<!--        <div class="generator-panel">-->
<!--          <div class="prompt-input-enhanced">-->
<!--            <el-input-->
<!--                v-model="prompt"-->
<!--                type="textarea"-->
<!--                :rows="5"-->
<!--                placeholder="描述您想要的AI头像（例如：赛博朋克风格，蓝发机械少女）"-->
<!--                resize="none"-->
<!--                class="prompt-textarea"-->
<!--            />-->
<!--            <div class="prompt-tips">-->
<!--              <el-tag type="info" size="small">推荐使用英文描述</el-tag>-->
<!--              <el-button link type="primary" @click="showPromptExamples">-->
<!--                查看示例-->
<!--              </el-button>-->
<!--            </div>-->
<!--          </div>-->

<!--          <div class="generation-controls">-->
<!--            <span style="font-size: 14px;color: #1baeae">输出数量：</span>-->
<!--            <el-select-->
<!--                v-model="batchSize"-->
<!--                style="width: 60px; margin-right: 30px;"-->
<!--                placeholder="数量"-->
<!--            >-->
<!--              <el-option-->
<!--                  v-for="num in [1, 2, 4]"-->
<!--                  :key="num"-->
<!--                  :label="`${num}`"-->
<!--                  :value="num"-->
<!--              />-->
<!--            </el-select>-->
<!--            <el-button-->
<!--                type="primary"-->
<!--                :loading="isGenerating"-->
<!--                :disabled="!prompt.trim()"-->
<!--                @click="generateAvatar"-->
<!--            >-->
<!--              {{ isGenerating ? '生成中...' : '立即生成' }}-->
<!--            </el-button>-->
<!--            <el-button @click="clearGeneration">-->
<!--              清空-->
<!--            </el-button>-->
<!--          </div>-->

<!--          <div v-if="generatedAvatars.length" class="generation-results">-->
<!--            <div class="result-grid">-->
<!--              <div-->
<!--                  v-for="(avatar, index) in generatedAvatars"-->
<!--                  :key="index"-->
<!--                  class="avatar-item"-->
<!--                  :class="{ selected: selectedAvatarIndex === index }"-->
<!--                  @click="selectedAvatarIndex = index"-->
<!--              >-->
<!--                <el-image-->
<!--                    :src="avatar"-->
<!--                    class="preview-image"-->
<!--                    fit="cover"-->
<!--                    :preview-src-list="generatedAvatars"-->
<!--                >-->
<!--                  <template #error>-->
<!--                    <div class="error-preview">-->
<!--                      <el-icon>-->
<!--                        <Warning/>-->
<!--                      </el-icon>-->
<!--                      <span>生成结果加载失败</span>-->
<!--                    </div>-->
<!--                  </template>-->
<!--                </el-image>-->
<!--                <div v-if="selectedAvatarIndex === index" class="selected-badge">-->
<!--                  <el-icon>-->
<!--                    <Check/>-->
<!--                  </el-icon>-->
<!--                </div>-->
<!--              </div>-->
<!--            </div>-->

<!--            <div v-if="selectedAvatarIndex !== null" class="preview-toolbar">-->
<!--              <el-tooltip content="下载选中图片">-->
<!--                <el-button-->
<!--                    type="success"-->
<!--                    :icon="Download"-->
<!--                    circle-->
<!--                    @click="showDownloadDialog"-->
<!--                />-->
<!--              </el-tooltip>-->
<!--              <el-tooltip content="设为头像">-->
<!--                <el-button-->
<!--                    type="primary"-->
<!--                    :icon="Check"-->
<!--                    circle-->
<!--                    @click="applyAsAvatar"-->
<!--                />-->
<!--              </el-tooltip>-->
<!--            </div>-->
<!--          </div>-->
<!--        </div>-->
<!--      </div>-->
    </div>

    <!-- 下载对话框 -->
<!--    <el-dialog-->
<!--        v-model="downloadVisible"-->
<!--        title="选择下载参数"-->
<!--        width="400px"-->
<!--        :close-on-click-modal="false"-->
<!--    >-->
<!--      <div class="download-options">-->
<!--        <div class="option-item">-->
<!--          <span class="option-label">图片尺寸：</span>-->
<!--          <el-select v-model="selectedSize">-->
<!--            <el-option-->
<!--                v-for="size in availableSizes"-->
<!--                :key="size"-->
<!--                :label="`${size}px`"-->
<!--                :value="size"-->
<!--            />-->
<!--          </el-select>-->
<!--        </div>-->
<!--        <div class="option-item">-->
<!--          <span class="option-label">图片格式：</span>-->
<!--          <el-radio-group v-model="selectedFormat">-->
<!--            <el-radio label="png">PNG</el-radio>-->
<!--            <el-radio label="jpg">JPG</el-radio>-->
<!--          </el-radio-group>-->
<!--        </div>-->
<!--      </div>-->
<!--      <template #footer>-->
<!--        <el-button @click="downloadVisible = false">取消</el-button>-->
<!--        <el-button type="primary" @click="handleDownload">-->
<!--          开始下载-->
<!--        </el-button>-->
<!--      </template>-->
<!--    </el-dialog>-->
  </div>
  <div class="footer">
    <div>社区养老服务整合平台</div>

  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {
  Upload,
  Download,
  Check,
  Picture,
  Warning
} from '@element-plus/icons-vue'
import {uploadImgServer} from "../../store/index.js"
import {getLoginerInfo, updateUser} from "../../service/userApi.js";
import {generateImageByDeepSeek} from "../../service/deepseekApi.js";

const userForm = reactive({
  id: 1,
  username: 'admin123',
  name: 'hzj',
  phone: '1231535332',
  email: '123456@qq.com',
  avatar: 'https://img.ixintu.com/download/jpg/20200910/f9256155491e54bf5e99bf29eece0156_512_512.jpg!ys',
  role: '用户',
  password: '123456'
})

const originalAvatar = ref('/default-avatar.jpg')
const generatedAvatars = ref([])
const selectedAvatarIndex = ref(null)
const prompt = ref('')
const batchSize = ref(4)
const isGenerating = ref(false)
const isSaving = ref(false)

const downloadVisible = ref(false)
const selectedSize = ref(1024)
const selectedFormat = ref('png')
const availableSizes = [256, 512, 1024]

// 新增下载对话框显示方法
const showDownloadDialog = () => {
  downloadVisible.value = true
}

// 登录用户详情查询接口
const getUserDetail = async () => {
  try {
    const res = await getLoginerInfo()
    userForm.id = res.data.id
    userForm.username = res.data.username
    userForm.name = res.data.name
    userForm.phone = res.data.phone
    userForm.email = res.data.email
    userForm.avatar = res.data.avatar
    userForm.role = res.data.role
    userForm.password = res.data.password
  } catch (error) {
    console.error('获取用户详情失败:', error)
  }
}

// 保存即修改用户信息
const updateUserInfo = async () => {
  const params = {
    id: userForm.id,
    name: userForm.name,
    username: userForm.username,
    avatar: userForm.avatar,
    phone: userForm.phone,
    email: userForm.email,
    password: userForm.password,
    role: userForm.role
  }
  await updateUser(params).then(() => {
    ElMessage.success('修改成功')
  })
}

const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过5MB!')
    return false
  }
  return true
}

// 头像上传成功回调
const handleUploadSuccess = (response) => {
  userForm.avatar = response.data
  ElMessage.success('头像上传成功')
}

const showPromptExamples = () => {
  ElMessageBox.alert('beautiful girl, young woman, office, anime style, iridescent effect, blue hour,' +
      ' rainy weather, 8k uhd, highly detailed, dreamy, ethereal, wide-angle lens, Japanese style, ' +
      'big eyes, surprised, blue hair, casual wear, glasses, peace sign', '提示示例', {})
}

// 清除生成结果
const clearGeneration = () => {
  originalAvatar.value = '/default-avatar.jpg'
  generatedAvatars.value = []
  selectedAvatarIndex.value = null
  prompt.value = ''
}

// 生成头像
const generateAvatar = async () => {
  try {
    isGenerating.value = true
    selectedAvatarIndex.value = null
    generatedAvatars.value = []
    const params = {
      imageSize: `${selectedSize.value}x${selectedSize.value}`,
      prompt: prompt.value,
      batchSize: batchSize.value,
    }
    const res = await generateImageByDeepSeek(params)
    if (res.data && res.data.length >= batchSize.value) {
      generatedAvatars.value = res.data.slice(0, batchSize.value)
    } else {
      ElMessage.error('操作过于频繁：', res.data.slice(0, 1).toString())
    }
  } catch (error) {
    ElMessage.error('操作过于频繁，请稍后重试')
  } finally {
    isGenerating.value = false
  }
}

// 上传头像
const applyAsAvatar = async () => {
  // 新增时效性提示弹窗
  await ElMessageBox.confirm(
      `
        <div class="expire-warning">
          <el-icon color="#e6a23c"><Warning /></el-icon>
          <h3>重要提示</h3>
          <p>AI生成的图片链接会在24小时后自动失效，如需永久使用</p>
          <p>建议操作流程：</p>
          <ol>
            <li>点击右下角下载按钮保存到本地</li>
            <li>通过左侧「上传头像」功能重新上传</li>
          </ol>
        </div>
      `,
      '上传注意!!!',
      {
        confirmButtonText: '仍然设置',
        cancelButtonText: '取消操作',
        dangerouslyUseHTMLString: true,
        type: 'warning'
      }
  )
  if (selectedAvatarIndex.value !== null) {
    userForm.avatar = generatedAvatars.value[selectedAvatarIndex.value]
    ElMessage.success('已设置为当前头像')
  }
}

// 下载头像
const handleDownload = () => {
  if (selectedAvatarIndex.value !== null) {
    const link = document.createElement('a')
    link.href = generatedAvatars.value[selectedAvatarIndex.value]
    link.download = `avatar-${selectedSize.value}px.${selectedFormat.value}`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    downloadVisible.value = false
  }
}

onMounted(() => {
  getUserDetail()
})
</script>

<style scoped>
.avatar-management-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
}

.main-layout {
  display: flex;
  gap: 30px;
}

.user-profile-section {
  flex: 1;
  width: 450px;
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.ai-generation-section {
  flex: 1;
  background: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.section-title {
  color: #333;
  border-left: 4px solid #409eff;
  padding-left: 12px;
  margin: 0 0 20px;
}

.avatar-preview-wrapper {
  position: relative;
  width: 160px;
  height: 160px;
  margin: 0 auto 20px;
  border-radius: 50%;
  overflow: hidden;
  cursor: pointer;
  transition: transform 0.3s;
}

.upload-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #fff;
  opacity: 0;
  transition: opacity 0.3s;
}

.avatar-preview-wrapper:hover .upload-mask {
  opacity: 1;
}

.generation-results {
  margin-top: 20px;
}

.result-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px; /* 这个控制图片之间的间距 */
  margin: 20px 0;
}

.avatar-item {
  position: relative;
  width: 100px;
  height: 100px;
  border: 2px solid transparent;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  margin: 0 auto;
  z-index: 1;
  transition: transform 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94); /* 使用更平滑的贝塞尔曲线 */
  transform-origin: center center; /* 明确指定缩放中心 */
}


.selected-badge {
  position: absolute;
  top: 8px;
  right: 8px;
  width: 24px;
  height: 24px;
  background: #409eff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.preview-toolbar {
  display: flex;
  justify-content: center;
  gap: 24px;
  margin-top: 20px;
}

.global-actions {
  margin-top: 20px;
  text-align: center;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.generation-controls {
  margin: 20px 0;
  text-align: center;
}

@media (max-width: 576px) {
  .avatar-preview-wrapper {
    width: 120px;
    height: 120px;
  }

  .el-form-item {
    margin-bottom: 18px;
  }
}

/* 新增提示框样式 */
.expire-warning {
  line-height: 1.8;

h3 {
  color: #e6a23c;
  margin: 10px 0;
}

ol {
  margin: 10px 0;
  padding-left: 20px;

li {
  margin-bottom: 8px;
}

}

.el-icon {
  font-size: 24px;
  vertical-align: middle;
}

}

.footer {
  position: fixed; /* 固定定位 */
  bottom: 0; /* 距离视口底部为 0 */
  left: 50%; /* 水平方向居中 */
  transform: translateX(-50%); /* 微调以确保完全居中 */
  font-size: 14px;
  display: flex;
  flex-direction: row; /* 水平排列 */
  justify-content: center;
  align-items: center;
  gap: 10px;
  width: 100%; /* 确保宽度占满整个视口 */
  box-sizing: border-box; /* 避免宽度计算问题 */
}

.beian-footer {
  bottom: 0;
  text-align: center;

a {
  color: #1D1D26;
  font-size: 14px;
  text-decoration-line: underline;

&:hover {
   color: #409EFF;
 }
}
}

</style>
